export default class MiUtil {
    /** 游戏设计分辨率 */
    private static _gameDr: cc.Size;


    public static loadScene(scene: string, cb?: any) {
        cc.director.loadScene(scene, () => {
            console.log(scene + ' loaded');

            this._gameDr = null;
            this.screenAdapter();

            if (cb) cb();
        });
    }

    /**
     * 屏幕适配
     * 参考 [麒麟子Cocos Creator实用技巧九：棋牌UI全分辨率适配方案](https://blog.csdn.net/qq_36720848/article/details/89742451?spm=1001.2014.3001.5501)
     */
    public static screenAdapter() {
        const canvas = cc.find('Canvas').getComponent(cc.Canvas);
        // 保存原始设计分辨率, 供屏幕大小变化时使用
        if (!this._gameDr) this._gameDr = canvas.designResolution;

        var frameSize = cc.view.getFrameSize();
        var frameWidth = frameSize.width;
        var frameHeight = frameSize.height;

        var finalWidth = frameWidth;
        var finalHeight = frameHeight;

        if ((frameWidth / frameHeight) > (this._gameDr.width / this._gameDr.height)) {
            //!#zh: 是否优先将设计分辨率高度撑满视图高度。 */
            //cvs.fitHeight = true;

            //如果更长，则用定高
            finalHeight = this._gameDr.height;
            finalWidth = finalHeight * frameWidth / frameHeight;
        } else {
            /*!#zh: 是否优先将设计分辨率宽度撑满视图宽度。 */
            //cvs.fitWidth = true;
            //如果更短，则用定宽
            finalWidth = this._gameDr.width;
            finalHeight = frameHeight / frameWidth * finalWidth;
        }

        canvas.designResolution = cc.size(finalWidth, finalHeight);
        canvas.node.width = finalWidth;
        canvas.node.height = finalHeight;
        canvas.node.emit('resize');
    }

    /**
     * 添加对齐组件
     * @param node 节点
     * @param target 对齐目标(默认直接父节点)
     */
     public static setWidget(node: cc.Node, target?: cc.Node): void {
        if (node.getComponent(cc.Widget)) return;
        
        const widget: cc.Widget = node.addComponent(cc.Widget);
        if (target) widget.target = target;
        widget.isAlignTop = true;
        widget.isAlignBottom = true;
        widget.isAlignLeft = true;
        widget.isAlignRight = true;
        widget.top = 0;
        widget.bottom = 0;
        widget.left = 0;
        widget.right = 0;
    }

    public static async asyncWrap<T, U = any>(promise: Promise<T>): Promise<[T | null, U | null]> {
        try {
            const data = await promise;
            const result: [T, null] = [data, null];
            return result;
        } catch (err) {
            const result_1: [null, U] = [null, err];
            return result_1;
        }
    }
}
